<template>
  <div class="signature">
    <el-image
          style="width: 100px; height: 50px"
          :src="applicantSignature"
    ></el-image>
    <!-- 无签名提示 -->
    <EsignatureTip ref="esignature-tip" :type-name="typeName"></EsignatureTip>
  </div>
</template>
<script>
import EsignatureTip from '../EsignatureTip/index.vue'
import { UserModel } from '@/models'
export default {
    name: 'Signature',
    components: {
        EsignatureTip
    },
    props: {
        typeName: {
            type: String,
            default: '申请'
        }
    },
    data() {
        return {
            applicantSignature: '',
            userModel: new UserModel(),
        }
    },
    created() {
        this.getHasUserInfo()
    },
    methods: {
        getHasUserInfo() {
            this.userModel.getHasUserInfo().then(res => {
                if (res.esignature) {
                    this.convertImageToBase64(res.esignature, (base64) => {
                        this.applicantSignature = base64
                        this.$emit('update:applicantSignature', base64)
                    }) 
                } else {
                    this.$refs['esignature-tip'].visible = true
                }
            })
        },
        // 图片地址转base64
        convertImageToBase64(url, callback) {
            const img = new Image()
            // imgUrl是一个完整的绝对路径，如果是开发环境，会存在跨域问题，
            // 这里移除前面的域名，通过本地代理解决跨域，线上都是一个域名不会跨域，不用处理
            let fullPath = url
            if (process.env.NODE_ENV === 'development') {
                fullPath = new URL(fullPath).pathname
            }
            img.src = fullPath

            // img.crossOrigin = 'Anonymous' 
            img.setAttribute('crossOrigin', 'anonymous') // 如果图片需要跨域访问
            img.onload = () => {
                const canvas = document.createElement('canvas')
                canvas.width = img.width
                canvas.height = img.height
                const ctx = canvas.getContext('2d')
                ctx.drawImage(img, 0, 0)
                const base64 = canvas.toDataURL('image/png')
                callback(base64)
            }
            img.onerror = () => {
                callback(null)
                console.error('无法加载图片: ', url)
            }
        },
    }
}
</script>
<style scoped lang="scss">

</style>
